package com.bluefox.modules.common.service.upload.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.bluefox.modules.common.config.AliyunOSSConfig;
import com.bluefox.modules.common.service.upload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: bluefox-parent
 * @description:
 * @author: Sun Feng
 * @create: 2020-06-30 15:52
 **/
@Component(value = "aliyunOSSFileUpload")
public class AliyunOSSFileUpload implements FileUpload {

    @Autowired
    private  AliyunOSSConfig aliyunOSSConfig;
    @Override
    public String upload(MultipartFile multipartFile, String extName) throws IOException {
        String realName = UUID.randomUUID().toString() + "." + extName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOSSConfig.getEndpoint() ,
                aliyunOSSConfig.getAccessKey(), aliyunOSSConfig.getAccessKeySecret());
        /**
         * 1、桶的名称
         * 2、文件存储的路径，以及文件真实名称
         * 3、文件的内容
         */
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOSSConfig.getBucketName(), aliyunOSSConfig.getKey()+realName, new ByteArrayInputStream(multipartFile.getBytes()));
        //...上传图片到阿里云...
        ossClient.putObject(putObjectRequest);

        ossClient.shutdown();
        // 返回文件真正调用的地址
        return aliyunOSSConfig.getBackurl()+ realName;
    }
}
